package com.hdd.biz.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdd.biz.app.dto.*;
import com.hdd.biz.app.entity.TopicModel;
import com.hdd.biz.app.mapper.APPPaintingWorksMapper;
import com.hdd.biz.app.mapper.AppFileInfoMapper;
import com.hdd.biz.app.mapper.AppMaterialKindMapper;
import com.hdd.biz.app.service.PublishService;
import com.hdd.biz.finance.dto.PaymetListRequest;
import com.hdd.biz.member.entity.Member;
import com.hdd.biz.member.service.MemberService;
import com.hdd.biz.painting.entity.*;
import com.hdd.biz.painting.mapper.PaintingTopicMapper;
import com.hdd.biz.painting.service.PaintingTopicLinkService;
import com.hdd.biz.painting.service.PaintingTopicService;
import com.hdd.biz.painting.service.UserFollowService;
import com.hdd.utils.BaiduUtils;
import com.hdd.utils.IdUtils;
import com.hdd.utils.wx.RedisUtil;
import com.hdd.utils.wx.WxMiniProgramCheckUtil;
import org.apache.commons.lang.StringUtils;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class PublishServiceImpl implements PublishService {

    @Autowired
    private AppMaterialKindMapper appMaterialKindMapper;
    @Autowired
    private AppFileInfoMapper fileInfoMapper;
    @Autowired
    private APPPaintingWorksMapper paintingWorksMapper;
    @Autowired
    private PaintingTopicMapper topicMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private WxMiniProgramCheckUtil wxMiniProgramCheckUtil;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PaintingTopicLinkService topicLinkService;
    @Autowired
    private PaintingTopicService topicService;

    @Override
    public AppResponse getFraming(FramingRequest request) {
        AppResponse response = new AppResponse();
        QueryWrapper<MaterialKind> wrapper = new QueryWrapper();
        wrapper.eq("type",request.getType());
        wrapper.eq("del_flag",0);
        wrapper.orderByDesc("sort");
        List<MaterialKind> list =  appMaterialKindMapper.selectList(wrapper);
        for(MaterialKind kind:list){
            kind.setMaterIalList(item(kind.getId()));
        }
        response.setItems(list);
        return response;
    }


    public List<FileInfo> item(String id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("material_kind_id",id);
        wrapper.eq("del_flag",0);
        wrapper.orderByDesc("sort");
        return fileInfoMapper.selectList(wrapper);
    }


    @Override
    public AppResponse getColor(FramingRequest request) {
        AppResponse response = new AppResponse();
        QueryWrapper<MaterialKind> wrapper = new QueryWrapper();
        wrapper.eq("cover_type",2);
        wrapper.eq("del_flag",0);
        wrapper.orderByAsc("sort");
        List<MaterialKind> list =  appMaterialKindMapper.selectList(wrapper);
        response.setItems(list);
        return response;
    }


    @Override
    public AppResponse saveOriginalPicture(SaveOriginalPictureRequest request) {
        AppResponse response = new AppResponse();
        PaintingWorks paintingWorks = new PaintingWorks();
        String id = IdUtils.getUUID();
        paintingWorks.setId(id);
        paintingWorks.setOriginalPainting(request.getOriginalPicture());
        paintingWorks.setUserId(request.getUserId());
        int rows = paintingWorksMapper.insert(paintingWorks);
        if(rows==0){
            response.setCode(-1000);
            response.setMessage("保存失败");
            return response;
        }
        response.setItem(id);
        return response;
    }


    @Override
    public AppResponse publish(PublishRequest request) throws Exception{
        AppResponse response = new AppResponse();

        Member member = memberService.findMemberByUid(request.getUserId());
        if(member==null){
            response.setCode(-1000);
            response.setMessage("用户不存在");
            return response;
        }

        if("F".equals(member.getStatus())){
            response.setCode(-1000);
            response.setMessage("禁止发布");
            return response;
        }


       boolean flag = BaiduUtils.check(request.getPainting());
        if(!flag){
            response.setCode(-1000);
            response.setMessage("图片内容违规");
            return response;
        }

        PaintingWorks paintingWorks = new PaintingWorks();
        String worksId = IdUtils.getUUID();
    try {
        paintingWorks.setId(worksId);
        paintingWorks.setIsOriginal(request.getIsOriginal());
        paintingWorks.setUserId(request.getUserId());
        paintingWorks.setPaintingNo(request.getPaintingNo());
        paintingWorks.setPainting(request.getPainting());
        paintingWorks.setPaintingName(request.getPaintingName());
        paintingWorks.setPaintingDescription(request.getPaintingDescription());
        paintingWorks.setOriginalPainting(request.getOriginalPainting());
        paintingWorks.setCreateTime(LocalDateTime.now());
        paintingWorks.setLatitude(request.getLatitude());
        paintingWorks.setLocation(request.getLocation());
        paintingWorks.setLongitude(request.getLongitude());
        paintingWorks.setDelFlag(0);
        paintingWorks.setShows(1);
        paintingWorks.setIstop("F");
        paintingWorks.setWikiId(request.getWikiId());
        paintingWorks.setAdopt(null);
        paintingWorks.setTopics(request.getTopicIds());
        paintingWorks.setRecommend(0);
        paintingWorks.setDraftInfo(request.getDraftInfo());

        if(StringUtils.isNotEmpty(request.getTopicIds())){
            String ids[] = request.getTopicIds().split(",");
            if(ids.length>20){
                response.setCode(-1000);
                response.setMessage("话题数量过多");
                return response;
            }
            topicLinkService.delTopicLinksBy(worksId);
            for(int i=0;i<ids.length;i++){
                topicLinkService.insert(worksId,ids[i]);
            }
        }

        if(StringUtils.isNotEmpty(request.getAuthor())){ //如果作者不为空
            //判断话题是否存在
            PaintingTopic topic =  topicService.findTopicByName(request.getAuthor().trim());

            QueryWrapper<PaintingTopic> wrapper = new QueryWrapper<>();
            wrapper.eq("name",request.getAuthor());
            List<PaintingTopic> topics = topicMapper.selectList(wrapper);
            if(!CollectionUtils.isEmpty(topics)){
                topicLinkService.insert(worksId,topics.get(0).getId()+"");
            }

            if(topic==null){//不存就创建
                topic = topicService.inset(request.getAuthor().trim(),request.getUserId());
                topicLinkService.insert(worksId,topic.getId()+"");
            }else{
                topicLinkService.insert(worksId,topic.getId()+"");
            }
            //存在就设置
        }

        if(StringUtils.isNotEmpty(request.getPaintingName())){
            WxMiniProgramCheckUtil.CheckResult checkResult = wxMiniProgramCheckUtil.msgSecCheck(request.getPaintingName()+request.getPaintingDescription());
            if(checkResult.getErrCode()>0){
                response.setMessage("内容描述违规!");
                response.setCode(-1000);
                return response;
            }
        }

        int row=0;
        if("T".equals(request.getIsDraft())){
            paintingWorks.setShows(0);
            if(StringUtils.isNotEmpty(request.getId())){
                QueryWrapper<PaintingWorks> wrapper = new QueryWrapper<>();
                wrapper.eq("id",request.getId());
                row =  paintingWorksMapper.update(paintingWorks,wrapper);
            }else{
                row = paintingWorksMapper.insert(paintingWorks);
            }
        }else{
            //判断作者是否信任的
            if("0".equals(member.getTrustType().toString())){// 0 信任 1不信任
                paintingWorks.setShows(2);
                paintingWorks.setRecommend(1);
                //发布了跟新通知
                redisUtil.set("update:"+request.getUserId(),worksId);
                List<UserFollow> userIds = userFollowService.userIds(request.getUserId());
                for(UserFollow u:userIds){
                    redisUtil.set("update:"+u.getUserId(),worksId);
                }
            }else{
                paintingWorks.setShows(1);
                paintingWorks.setRecommend(0);
            }
            row = paintingWorksMapper.insert(paintingWorks);
        }

        //图片审核
        if(row==0){
            response.setMessage("保存失败!");
            response.setCode(-1000);
            return response;
        }
    }catch (Exception e){
        e.printStackTrace();
        log.error("发布作品失败");
        response.setMessage("保存失败!");
        response.setCode(-1000);
        return response;
    }

        response.setItem(worksId);
        return response;
    }


    @Override
    public AppResponse addTopicForUpdate(TopicsRequest request) {
        AppResponse response = new AppResponse();

        topicLinkService.insert(request.getWorksId(),request.getId()+"");
        return response;
    }

    @Override
    public AppResponse update(PublishRequest request) throws Exception {
        AppResponse response = new AppResponse();

        Member member = memberService.findMemberByUid(request.getUserId());
        if(member==null){
            response.setCode(-1000);
            response.setMessage("用户不存在");
            return response;
        }

        if("F".equals(member.getStatus())){
            response.setCode(-1000);
            response.setMessage("禁止编辑");
            return response;
        }


        boolean flag = BaiduUtils.check(request.getPainting());
        if(!flag){
            response.setCode(-1000);
            response.setMessage("图片内容违规");
            return response;
        }

        PaintingWorks paintingWorks = new PaintingWorks();
        try {
            paintingWorks.setId(request.getId());
            paintingWorks.setIsOriginal(request.getIsOriginal());
            paintingWorks.setUserId(request.getUserId());
            paintingWorks.setPaintingNo(request.getPaintingNo());
            paintingWorks.setPainting(request.getPainting());
            paintingWorks.setPaintingName(request.getPaintingName());
            paintingWorks.setPaintingDescription(request.getPaintingDescription());
            paintingWorks.setOriginalPainting(request.getOriginalPainting());
            paintingWorks.setCreateTime(LocalDateTime.now());
            paintingWorks.setLatitude(request.getLatitude());
            paintingWorks.setLocation(request.getLocation());
            paintingWorks.setLongitude(request.getLongitude());
            paintingWorks.setDelFlag(0);
            paintingWorks.setShows(1);
            paintingWorks.setIstop("F");
            paintingWorks.setAdopt("R");
            paintingWorks.setWikiId(request.getWikiId());
            paintingWorks.setTopics(request.getTopicIds());
            paintingWorks.setRecommend(0);
            paintingWorks.setDraftInfo(request.getDraftInfo());
            String ids[] = request.getTopicIds().split(",");
            if(StringUtils.isNotEmpty(request.getTopicIds())){
                if(ids.length>20){
                    response.setCode(-1000);
                    response.setMessage("话题数量过多");
                    return response;
                }
            }

            topicLinkService.delTopicLinksBy(request.getId());
            if(StringUtils.isNotEmpty(request.getTopicIds())){
                topicLinkService.delTopicLinksBy(request.getId());
                for(int i=0;i<ids.length;i++){
                    topicLinkService.insert(request.getId(),ids[i]);
                }
            }

            if(StringUtils.isNotEmpty(request.getPaintingName())){
                WxMiniProgramCheckUtil.CheckResult checkResult = wxMiniProgramCheckUtil.msgSecCheck(request.getPaintingName()+request.getPaintingDescription());
                if(checkResult.getErrCode()>0){
                    response.setMessage("内容描述违规!");
                    response.setCode(-1000);
                    return response;
                }
            }
            if(StringUtils.isNotEmpty(request.getAuthor())){ //如果作者不为空
                //判断话题是否存在
                PaintingTopic topic =  topicService.findTopicByName(request.getAuthor().trim());
                QueryWrapper<PaintingTopic> wrapper = new QueryWrapper<>();
                wrapper.eq("name",request.getAuthor());
                List<PaintingTopic> topics = topicMapper.selectList(wrapper);
                if(!CollectionUtils.isEmpty(topics)){
                    topicLinkService.insert(request.getId(),topics.get(0).getId()+"");
                }
                if(topic==null){//不存就创建
                    topic = topicService.inset(request.getAuthor().trim(),request.getUserId());
                    topicLinkService.insert(request.getId(),topic.getId()+"");
                }else{
                    topicLinkService.insert(request.getId(),topic.getId()+"");
                }
                //存在就设置
            }

            int row=0;
            //判断作者是否信任的
            if("0".equals(member.getTrustType().toString())){// 0 信任 1不信任
                paintingWorks.setShows(2);
                paintingWorks.setRecommend(1);
            }else{
                paintingWorks.setShows(1);
                paintingWorks.setRecommend(0);
            }

            QueryWrapper<PaintingWorks> wrapper = new QueryWrapper<>();
            wrapper.eq("id",request.getId());
            row = paintingWorksMapper.update(paintingWorks,wrapper);


            //图片审核
            if(row==0){
                response.setMessage("保存失败!");
                response.setCode(-1000);
                return response;
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("发布作品失败");
            response.setMessage("保存失败!");
            response.setCode(-1000);
            return response;
        }

        response.setItem(request.getId());
        return response;
    }


    @Override
    public AppResponse getPriorTopic(TopicsRequest request) {
        AppResponse response = new  AppResponse();
        QueryWrapper<PaintingTopic> wrapper = new QueryWrapper();
        wrapper.eq("status","T");
        if(!StringUtil.isNullOrEmpty(request.getName())){
            wrapper.like("name",request.getName());
        }else{
            wrapper.eq("prior","T");
        }
        wrapper.orderByDesc("sort_no");
        wrapper.last("limit 50");
        response.setItems(convertTopic(topicMapper.selectList(wrapper)));
        return response;
    }


    @Override
    public AppResponse getTopics(TopicsRequest request) {
        AppResponse response = new  AppResponse();
        QueryWrapper<PaintingTopic> wrapper = new QueryWrapper();
        wrapper.eq("status","T");
        if(!StringUtil.isNullOrEmpty(request.getName())){
            wrapper.like("name",request.getName());
        }
        wrapper.orderByDesc("sort_no");
        response.setItems(convertTopic(topicMapper.selectList(wrapper)));
        return response;
    }



    @Override
    public AppResponse addTopic(TopicsRequest request) {
        AppResponse response = new  AppResponse();
        PaintingTopic paintingTopic = new PaintingTopic();
        paintingTopic.setName(request.getName());

        QueryWrapper<PaintingTopic> wrapper = new QueryWrapper<>();
        wrapper.eq("name",request.getName());
        if(topicMapper.selectCount(wrapper)>0){
            response.setCode(-1000);
            response.setMessage("已存在相同话题!");
            return response;
        }

        paintingTopic.setUserId(request.getUserId());
        paintingTopic.setStatus("T");
        topicMapper.insert(paintingTopic);



       if(StringUtils.isNotEmpty(request.getWorksId())){
           topicLinkService.insert(request.getWorksId(),paintingTopic.getId()+"");
       }

        response.setItem(paintingTopic);
        return response;
    }




    @Override
    public List<TopicModel> getTopics(String ids) {
        log.info("ids:"+ids);
        if(StringUtils.isEmpty(ids)){
            return null;
        }
        QueryWrapper<PaintingTopic> wrapper = new QueryWrapper();
        String id1[] = ids.split(",");
        List<Integer> topIds = new ArrayList<>();
        for(int i=0;i<id1.length;i++){
            if(StringUtils.isNotEmpty(id1[i])){
                topIds.add(Integer.parseInt(id1[i]));
            }
        }
        wrapper.eq("status","T");
        if(StringUtils.isNotEmpty(ids)){
            wrapper.in("id",topIds);
            wrapper.orderByAsc("sort_no");
            return convertTopic(topicMapper.selectList(wrapper));

        }
        return null;
    }

    @Override
    public List<TopicModel> getTopicsByWorkId(String workId) {
        QueryWrapper<PaintingTopic> wrapper = new QueryWrapper();

        List<String> ids = topicLinkService.getids(workId);
        if(CollectionUtils.isEmpty(ids)){
            return  null;
        }
        wrapper.in("id",topicLinkService.getids(workId));
        wrapper.orderByDesc("sort_no");
        return convertTopic(topicMapper.selectList(wrapper));
    }


    public List<TopicModel> convertTopic(List<PaintingTopic> list){
        List<TopicModel> topicModels = new ArrayList<>();
        TopicModel topicModel = null;
        for(PaintingTopic topic:list){
            topicModel = new TopicModel();
            topicModel.setId(topic.getId());
            topicModel.setName(topic.getName());
            topicModel.setColor(topic.getColor());
            topicModel.setRemarks(topic.getRemarks());
            topicModels.add(topicModel);
        }
        return topicModels;
    }


    @Override
    public AppResponse uploadVoice(PaymetListRequest request) {
        AppResponse response = new AppResponse();
        PaintingWorks paintingWorks = new PaintingWorks();
        paintingWorks.setMediaUrl(request.getVoiceUrl());
        paintingWorks.setMediaTime(request.getMediaTime());
        QueryWrapper<PaintingWorks> wrapper = new QueryWrapper<>();
        wrapper.eq("id",request.getWorksId());
        paintingWorksMapper.update(paintingWorks,wrapper);
        return response;
    }

    @Override
    public AppResponse delTopic(TopicsRequest request) {
        AppResponse response = new AppResponse();
        topicLinkService.delTopic(request.getWorksId(),request.getId()+"");
        return response;
    }
}
